package com.ssyu.examination.assist.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.ssyu.examination.assist.entity.AssistMsgEntity;
import com.ssyu.examination.conmmon.PageModel;
import com.ssyu.examination.conmmon.util.DBUtil;
import com.ssyu.examination.system.entity.SystemEntiy;

public class AssistMsgService {

	/**
	 * 分页查询站内信息
	 * 
	 * @param page
	 * @param rows
	 * @param state
	 * @param clazz
	 * @return
	 */
	public PageModel<AssistMsgEntity> listMsg(int page, int rows, AssistMsgEntity assistMsgEntity, String code,
			int state) {
		List<Object> objects = new ArrayList<Object>();

		StringBuilder sb = new StringBuilder();
		sb.append(
				"SELECT m.*,u.name As 'sys_user__name',u.code As 'sys_user__code',r.name AS 'sys_role__name' FROM assist_message m,sys_role r,sys_user u ");

		sb.append("WHERE r.id = u.role_id AND m.sender_id= u.id ");

		String title = assistMsgEntity.getTitle();
		if (StringUtils.isNotBlank(title) && "0".equals(title) == false) {
			sb.append("AND m.title like ? ");
			objects.add("%" + title + "%");
		}

		String style = assistMsgEntity.getStyle();
		if (StringUtils.isNotBlank(style) && "0".equals(style) == false) {
			if ("1".equals(style)) {
				sb.append("AND m.sender_id in(SELECT id FROM sys_user WHERE code = ?) ");
				objects.add(code);
			} else if ("2".equals(style)) {
				sb.append("AND m.sender_id not in(SELECT id FROM sys_user WHERE code = ?) ");
				objects.add(code);
			}
		}

		String role = assistMsgEntity.getSysRole__name();
		if (StringUtils.isNotBlank(role) && "0".equals(role) == false) {
			sb.append("AND r.name in(?) ");
			objects.add(role);
		}

		if (state != 0) {
			sb.append("AND m.state in(?) ");
			objects.add(state);
		}

		String expireTime = assistMsgEntity.getExpireTime();
		if (StringUtils.isNotBlank(expireTime) && "0".equals(expireTime) == false) {
			if ("1".equals(expireTime)) {
				sb.append("AND m.expire_time <= now() ");
			} else if ("2".equals(expireTime)) {
				sb.append("AND m.expire_time >= now() ");
			}
		}
		sb.append(" ORDER BY sender_id <> (SELECT id FROM sys_user WHERE code = ?),send_time DESC LIMIT ?,?");
		objects.add(code);
		objects.add((page - 1) * rows);
		objects.add(rows);
		return DBUtil.executeQueryByPage(AssistMsgEntity.class, sb.toString(), objects);
	}

	/**
	 * 删除站内信息
	 * 
	 * @param id
	 * @return
	 */
	public int deleteMsg(String id) {
		return DBUtil.executeUpdate("DELETE FROM assist_message WHERE id = ?", id);
	}

	/**
	 * 站内信息生效操作
	 * 
	 * @param id
	 * @return
	 */
	public int effectMsg(String id) {
		return DBUtil.executeUpdate("UPDATE assist_message SET state = 1 WHERE id = ?", id);
	}

	/**
	 * 站内消息详情查看
	 * 
	 * @param id
	 * @return
	 */
	public List<SystemEntiy> detailPersonMsg(String id) {

		AssistMsgEntity personArray = DBUtil.getUniqueResult(AssistMsgEntity.class,
				"SELECT receiver_user_ids FROM assist_message WHERE id = ?", id);
		String str = personArray.getReceiverUserIds().toString();

		// System.out.println("str" + str);
		String[] temp = str.split(",");
		// System.out.println(Arrays.toString(temp));

		StringBuffer sb = new StringBuffer();
		sb.append(
				"SELECT u.*,b.name AS 'class__name' FROM sys_user u LEFT JOIN (SELECT name,id FROM sys_class) b ON b.id = u.class_id WHERE u.id in(");
		for (int i = 0; i < temp.length; i++) {
			if (i == temp.length - 1) {
				sb.append(temp[i]);
			} else {
				sb.append(temp[i] + ",");
			}
		}
		sb.append(")");
		// System.out.println(sb);
		return DBUtil.executeQuery(SystemEntiy.class, sb.toString());

	}

	public AssistMsgEntity detailMsg(String id) {

		return DBUtil.getUniqueResult(AssistMsgEntity.class,
				"SELECT a.id,a.title,a.content,a.send_time,a.expire_time,a.state,(SELECT name FROM sys_user WHERE id = a.receiver_user_ids) AS 'receive__name',(SELECT name FROM sys_class WHERE id = a.receiver_class_ids) AS 'class__name',u.name As 'sys_user__name',u.code As 'sys_user__code',r.name AS 'sys_role__name' FROM assist_message a,sys_user u,sys_role r WHERE u.role_id = r.id AND a.sender_id = u.id AND a.id = ? ",
				id);
	}

	/**
	 * 站内消息新增
	 * 
	 * @param receiveMan
	 * @param state
	 * @return
	 */

	// 发送者Id
	public static String getRecevierMsgId(String[] receiveMan) {

		StringBuffer sb = new StringBuffer();
		StringBuffer ids = new StringBuffer();
		sb.append("SELECT id FROM sys_user WHERE code in(");
		int len = receiveMan.length;
		for (int i = 0; i < len; i++) {
			int site = receiveMan[i].indexOf(":");
			if (site != -1) {
				if (receiveMan[i] != null) {
					String substring = receiveMan[i].substring(receiveMan[i].indexOf(":") + 1,
							receiveMan[i].indexOf(")"));
					if (i == len - 1) {
						sb.append(substring);
					} else {
						sb.append(substring + ",");
					}
				}
			} else {
				SystemEntiy managerCode = DBUtil.getUniqueResult(SystemEntiy.class,
						"SELECT code FROM sys_user WHERE name = ?", receiveMan[i]);
				if (managerCode != null) {
					if (i == len - 1) {
						sb.append(managerCode.getCode());
					} else {
						sb.append(managerCode.getCode() + ",");
					}

				}
			}
		}
		sb.append(")");
		// System.out.println(sb.toString());
		List<SystemEntiy> userIds = DBUtil.executeQuery(SystemEntiy.class, sb.toString());
		if (userIds != null) {
			for (int i = 0; i < userIds.size(); i++) {
				if (i == userIds.size() - 1) {
					ids.append(userIds.get(i).getId());
				} else {
					ids.append(userIds.get(i).getId() + ",");
				}

			}
		}
		return ids.toString();
	}

	// 接收者Id
	public static AssistMsgEntity getSenderMsgId(AssistMsgEntity assistMsgEntity, String code) {

		return DBUtil.getUniqueResult(AssistMsgEntity.class, "SELECT id FROM sys_user WHERE code = ?", code);
	}

	// 接受者班级
	public static String getClazzId(String[] receiveMan) {

		StringBuffer sb = new StringBuffer();
		StringBuffer ids = new StringBuffer();
		sb.append("SELECT id FROM sys_user WHERE code in(");
		for (int i = 0; i < receiveMan.length; i++) {
			String string = receiveMan[i];
			int site = receiveMan[i].indexOf(":");
			if (site != -1) {
				String substring = string.substring(string.indexOf(":") + 1, string.indexOf(")"));
				if (i == receiveMan.length - 1) {
					sb.append(substring);
				} else {
					sb.append(substring + ",");
				}

			} else if ((site == -1)) {
				SystemEntiy managerCode = DBUtil.getUniqueResult(SystemEntiy.class,
						"SELECT code FROM sys_user WHERE name = ?", string);
				if (managerCode != null) {
					if (i == receiveMan.length - 1) {
						sb.append(managerCode.getCode());
					} else {
						sb.append(managerCode.getCode() + ",");
					}

				}
			}
		}
		sb.append(")");
		List<SystemEntiy> userIds = DBUtil.executeQuery(SystemEntiy.class, sb.toString());
		for (int i = 0; i < userIds.size(); i++) {
			if (i == userIds.size() - 1) {
				ids.append(userIds.get(i).getId());
			} else {
				ids.append(userIds.get(i).getId() + ",");
			}

		}
		return ids.toString();
	}

	public int addMsg(AssistMsgEntity assistMsgEntity, int state, String[] receiveMan, String code) {
		List<Object> paramList = new ArrayList<>();

		paramList.add(assistMsgEntity.getTitle());
		paramList.add(assistMsgEntity.getContent());

		paramList.add(getSenderMsgId(assistMsgEntity, code).getId());
		// System.out.println(getSenderMsgId(assistMsgEntity, code).getId()
		// + "getSenderMsgId(assistMsgEntity, code).getId()");

		paramList.add(getRecevierMsgId(receiveMan));

		paramList.add(assistMsgEntity.getExpireTime());
		paramList.add(state);

		return DBUtil.executeUpdate("INSERT INTO assist_message VALUES(NULL,?,?,NOW(),?,?,NULL,?,?)", paramList);
	}

	/**
	 * 站内消息修改
	 * 
	 * @param assistMsgEntity
	 * @param state
	 * @param receiveMan
	 * @param systemCode
	 * @return
	 */
	public int updateMsg(AssistMsgEntity assistMsgEntity, int state, String[] receiveMan, String systemCode, int id) {
		List<Object> paramList = new ArrayList<>();

		paramList.add(assistMsgEntity.getTitle());
		paramList.add(assistMsgEntity.getContent());
		paramList.add(assistMsgEntity.getExpireTime());
		paramList.add(getClazzId(receiveMan).toString());
		paramList.add(state);
		paramList.add(id);

		return DBUtil.executeUpdate(
				"UPDATE assist_message SET title=?,content=?,expire_time=?,receiver_user_ids=?,state=? WHERE id=?",
				paramList);
	}
}
